package com.dlc.shop.groupbuy.api.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.app.vo.GroupActivityVO;
import com.dlc.shop.bean.app.vo.GroupSkuVO;
import com.dlc.shop.bean.app.vo.SkuVO;
import com.dlc.shop.bean.enums.ProdType;
import com.dlc.shop.bean.event.LoadProdActivistEvent;
import com.dlc.shop.bean.order.LoadProdActivistOrder;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.groupbuy.common.api.dto.ApiGroupActivityDto;
import com.dlc.shop.groupbuy.common.api.dto.ApiJoinGroupTeamDto;
import com.dlc.shop.groupbuy.common.enums.GroupActivityStatusEnum;
import com.dlc.shop.groupbuy.common.enums.TeamStatusEnum;
import com.dlc.shop.groupbuy.common.model.GroupTeam;
import com.dlc.shop.groupbuy.common.service.GroupActivityService;
import com.dlc.shop.groupbuy.common.service.GroupTeamService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 加载商品团购信息
 * @author yami
 */
@Component("groupProdActivistListener")
@AllArgsConstructor
public class LoadProdActivistListener {

    private GroupActivityService groupActivityService;

    private GroupTeamService groupTeamService;

    private final Logger log = LoggerFactory.getLogger(this.getClass());



    @EventListener(LoadProdActivistEvent.class)
    @Order(LoadProdActivistOrder.DEFAULT)
    public void loadProdGroupHandle(LoadProdActivistEvent event) {
        // 不是团购商品，不用处理
        if (!Objects.equals(event.getProdType(), ProdType.PROD_TYPE_GROUP.value())) {
            return;
        }

        // 查询拼团活动信息
        ApiGroupActivityDto apiGroupActivityDto = groupActivityService.getByProdId(event.getProdId());

        GroupActivityVO groupActivityVO = BeanUtil.map(apiGroupActivityDto, GroupActivityVO.class);
        if(Objects.nonNull(groupActivityVO)){
            Long successNum = groupTeamService.count(new LambdaQueryWrapper<GroupTeam>()
                    .eq(GroupTeam::getStatus, 2)
                    .eq(GroupTeam::getProdId, event.getProdId()));
            groupActivityVO.setSuccessNum(successNum.intValue());
        }
        long currentTimeMillis = System.currentTimeMillis();

        // 无法获取团购信息、团购没有启用、当前时间大于活动结束时间， 则不添加活动信息
        boolean unActivity = Objects.isNull(apiGroupActivityDto)  ||
                !Objects.equals(apiGroupActivityDto.getStatus(), GroupActivityStatusEnum.ENABLE.value()) ||
                currentTimeMillis > groupActivityVO.getEndTime().getTime();
        // 没有开启预热且开始时间未到
        boolean noPreheatAnd = false;
        if (Objects.nonNull(apiGroupActivityDto)){
            log.info("拼团活动信息不为空");
            noPreheatAnd = Objects.equals(apiGroupActivityDto.getIsPreheat(), 0)
                    && currentTimeMillis < groupActivityVO.getStartTime().getTime();
        }
        if (unActivity || noPreheatAnd) {
            return;
        }
        // 插入sku信息
        Map<Long, SkuVO> skuMap = event.getProductVO().getSkuList().stream().collect(Collectors.toMap(SkuVO::getSkuId, s -> s));
        Iterator<GroupSkuVO> iterator = groupActivityVO.getGroupSkuList().iterator();
        while (iterator.hasNext()) {
            GroupSkuVO groupSkuVO = iterator.next();
            // 启用的sku中没有包含该团购sku，则删除该sku
            if (!skuMap.containsKey(groupSkuVO.getSkuId())) {
                iterator.remove();
                continue;
            }
            SkuVO skuDto = skuMap.get(groupSkuVO.getSkuId());
            groupSkuVO.setStocks(skuDto.getStocks());
            groupSkuVO.setPic(skuDto.getPic());
            groupSkuVO.setPrice(skuDto.getPrice());
            groupSkuVO.setProperties(skuDto.getProperties());
            groupSkuVO.setSkuName(skuDto.getSkuName());
        }

        // 获取拼团队伍
        ApiJoinGroupTeamDto joinTeam = groupTeamService.getJoinGroupTeamHasMaxNum(groupActivityVO.getGroupActivityId());
        if (joinTeam != null) {
            GroupTeam groupTeam = groupTeamService.getById(joinTeam.getJoinGroupTeamId());
            if (Objects.equals(groupTeam.getStatus(), TeamStatusEnum.IN_GROUP.value())) {
                groupActivityVO.setJoinGroupTeamId(joinTeam.getJoinGroupTeamId());
            }
            groupActivityVO.setProdCount(joinTeam.getProdCount());
        }

        // 获取商品活动最低价
        event.getProductVO().setGroupActivityVO(groupActivityVO);
    }

}
